import time

from selenium import webdriver

from baseTools.my_logger import logger
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
import traceback
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

from config import index_url
from page import BasePageElement
from selenium.webdriver import ActionChains


# 该方法自动执行或强制执行
def create_driver():
    """
    初始化浏览器对象，设置页面最大化，设置隐式等待10s
    """
    logger.info("初始化浏览器对象，设置页面最大化，设置隐式等待10s")
    try:
        driver = webdriver.Chrome(service=Service(r"C:\Program Files\Google\Chrome\Application\chromedriver.exe"))
        # self.driver = webdriver.Chrome(service=Service(r"C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe"))

        # 设置页面最大化
        driver.maximize_window()
        # 设置隐式等待
        driver.implicitly_wait(10)
    except:
        logger.error("初始化浏览器失败，请检查配置在尝试")
        logger.error(traceback.format_exc())
        raise "浏览器初始化失败"
    return driver



class BasePage():

    def __init__(self,driver):
        self.driver = driver

    # # 该方法自动执行或强制执行
    # def __init__(self):
    #     """
    #     初始化浏览器对象，设置页面最大化，设置隐式等待10s
    #     """
    #     logger.info("初始化浏览器对象，设置页面最大化，设置隐式等待10s")
    #     try:
    #         self.driver = webdriver.Chrome(service=Service(r"C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe"))
    #         # self.driver = webdriver.Chrome(service=Service(r"C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe"))
    #
    # #       设置页面最大化
    #         self.driver.maximize_window()
    #
    #         # 设置隐式等待
    #         self.driver.implicitly_wait(10)
    #     except:
    #         logger.error("初始化浏览器失败，请检查配置在尝试")
    #         logger.error(traceback.format_exc())
    #         raise "浏览器初始化失败"
#
# basePage()
# time.sleep(5)

    def my_get_url(self, url):
        """
        打开指定页面
        :param url:页面的url
        :return:
        """
        logger.info("打开页面：{}".format(url))
        try:
            self.driver.get(url)
        except:
            logger.error("打开页面失败，报错信息为：{}".format(traceback.format_exc()))
            raise "页面打开失败"

    def  my_find_element(self, ele, time_out = 10, time_c = 0.5):
        """
        查找元素封装
        :param ele:元素表达式，例如：(BY.ID, "kw")
        :param time_out:显示等待时间，默认10s
        :param time_c:显示等待检查频率，默认0.5s
        :return:
        """
        logger.info("查找元素，元素定位表达式：{}".format(ele))
        try:
            self.element = WebDriverWait(self.driver, time_out, time_c).until(EC.presence_of_element_located(ele))
        except:
            logger.warning("元素定位失败，错误信息为：{}".format(traceback.format_exc()))
            raise "元素定位失败"

    def  my_find_elements(self, ele):
        """
        查找一组元素封装
        :param ele:元素表达式，例如：(BY.ID, "kw")
        :param time_out:显示等待时间，默认10s
        :param time_c:显示等待检查频率，默认0.5s
        :return:
        """
        logger.info("查找元素，元素定位表达式：{}".format(ele))
        try:
            self.elements = self.driver.find_elements(ele)
        except:
            logger.warning("元素定位失败，错误信息为：{}".format(traceback.format_exc()))
            raise "元素定位失败"

    def my_click(self, ele, **kwargs):
        """
        点击元素封装
        :param ele:
        :param kwargs:
        :return:
        """
        # 查找my_find_element的属性，这个属性就是点击方法的需要点击元素的定位传给点击方法
        self.my_find_element(ele, **kwargs)
        # 点击
        logger.info("点击元素")
        self.element.click()

    def my_send_keys(self, ele, value,**kwargs):
        """
        元素输入内容方法封装
        :param ele:
        :param kwargs:
        :return:
        """
        self.my_find_element(ele, **kwargs)
        # 输入内容
        logger.info("元素输入内容：{}".format(value))
        self.element.clear()
        self.element.send_keys(value)

    def into_index_page(self):
        """
        进入项目首页
        :return:
        """
        self.my_get_url(index_url)

    def my_get_tip_text(self):
        return self.my_get_element_text(ele=BasePageElement.tip_ele)

    def my_move_to_element(self, ele, **kwargs):
        """
        鼠标移动至定位元素
        :param ele:
        :param kwargs:
        :return:
        """
        self.my_find_element(ele, **kwargs)
        ActionChains(self.driver).move_to_element(self.element).perform()

    def my_get_cookies(self):
        """
        获取cookies方法的封装
        :return:
        """
        self.cookies = self.driver.get_cookies()
        logger.info("获取cookies的内容：{}".format(self.cookies))

    def my_set_cookies(self, cookies):
        """
        批量设置cookies
        :param cookies:
        :return:
        """
        for cookie in cookies:
            self.driver.add_cookie(cookie)
        self.driver.refresh()
        logger.info("cookie设置成功")

    def my_get_element_atr(self, ele, atr, **kwargs):
        """
        获取元素指定属性值
        :param ele:
        :param atr:
        :param kwargs:
        :return:
        """
        self.my_find_element(ele, **kwargs)
        return self.driver.get_attribute(atr)

    def my_get_element_text(self, ele, **kwargs):
        """
        获取文本信息
        :param ele:
        :param kwargs:
        :return:
        """
        self.my_find_element(ele, **kwargs)
        return self.element.text
        logger.info("获取文本信息：{}".format(self.element.text))


    # def __del__(self):
    #     logger.info("关闭浏览器驱动")
    #     self.driver.quit()

# driver = create_driver()
# page_obj = BasePage(driver)
# # #
# # 打开企业微信首页
# page_obj.my_get_url("https://work.weixin.qq.com/wework_admin/frame")
# time.sleep(10)
# # 获取cookies
# page_obj.my_get_cookies()
# # # 打印cookies
# print("cookies = ", page_obj.cookies)
# cookies =[{'domain': '.work.weixin.qq.com', 'httpOnly': False, 'name': 'wwrtx.cs_ind', 'path': '/', 'sameSite': 'Lax', 'secure': False, 'value': ''}, {'domain': '.work.weixin.qq.com', 'expiry': 1779248069, 'httpOnly': False, 'name': 'wwrtx.c_gdpr', 'path': '/', 'sameSite': 'None', 'secure': True, 'value': '0'}, {'domain': '.work.weixin.qq.com', 'httpOnly': False, 'name': 'wxpay.vid', 'path': '/', 'sameSite': 'Lax', 'secure': False, 'value': '1688858210669890'}, {'domain': '.work.weixin.qq.com', 'httpOnly': False, 'name': 'wwrtx.vid', 'path': '/', 'sameSite': 'Lax', 'secure': False, 'value': '1688858210669890'}, {'domain': '.work.weixin.qq.com', 'httpOnly': False, 'name': 'wxpay.corpid', 'path': '/', 'sameSite': 'Lax', 'secure': False, 'value': '1970325389016159'}, {'domain': '.work.weixin.qq.com', 'httpOnly': True, 'name': 'wwrtx.ltype', 'path': '/', 'sameSite': 'Lax', 'secure': False, 'value': '1'}, {'domain': '.work.weixin.qq.com', 'httpOnly': True, 'name': 'wwrtx.sid', 'path': '/', 'sameSite': 'Lax', 'secure': False, 'value': 'tXBa3SyWm3dEHQMFo8chTpUQo7BVTpTGDOMzEWwZbs8w_kRBuxM2n-opYyb9DTYWnrcmgFS8R545A6--JNryyQ'}, {'domain': '.work.weixin.qq.com', 'httpOnly': True, 'name': 'wwrtx.vst', 'path': '/', 'sameSite': 'Lax', 'secure': False, 'value': 'qvxJ3vDOc5CXLczNtpjBpcvFmaZd9VnISYE7Z8XlNsvREaaeoFoaf9T213oZOHD00rg_dnVA7sdGyLPQ_IuJhimVA72KJZiZwTEkvSCXRUku519TsgAJW9A2GkiBwYX-YBHGMp_dlM9Z763qydEMBQatRT_MSfk_M2uJwI1BG17_bl4YJhXJJqJhBPjeQYWONnSKZzuN9d8auCIS4XYI6sXa1YHnUswPVa1aWz998HWDbljG0_TZx1koAmr5pVNeV98QxEquOJHRDQ92vWN2QCW3_7rGjSKWJ9hYunIokLE'}, {'domain': '.work.weixin.qq.com', 'httpOnly': True, 'name': 'wwrtx.ref', 'path': '/', 'sameSite': 'Lax', 'secure': False, 'value': 'direct'}, {'domain': '.work.weixin.qq.com', 'httpOnly': True, 'name': 'wwrtx.logined', 'path': '/', 'sameSite': 'Lax', 'secure': False, 'value': 'true'}, {'domain': '.work.weixin.qq.com', 'expiry': 1750304081, 'httpOnly': False, 'name': 'wwrtx.i18n_lan', 'path': '/', 'sameSite': 'Lax', 'secure': False, 'value': 'zh'}, {'domain': '.work.weixin.qq.com', 'httpOnly': True, 'name': 'wwrtx.refid', 'path': '/', 'sameSite': 'Lax', 'secure': False, 'value': '02069642'}, {'domain': '.work.weixin.qq.com', 'expiry': 1750304069, 'httpOnly': False, 'name': 'ww_lang', 'path': '/', 'sameSite': 'None', 'secure': True, 'value': 'cn,zh'}]
# page_obj.my_set_cookies(cookies)
# time.sleep(5)
